import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ExamRecordDAO {

    public ExamRecord getExamRecord(int examId, int studentId) {
        String sql = "SELECT * FROM exam_records WHERE exam_id = ? AND student_id = ?";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examId);
            stmt.setInt(2, studentId);

            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                ExamRecord record = new ExamRecord();
                record.setId(rs.getInt("id"));
                record.setExamId(rs.getInt("exam_id"));
                record.setStudentId(rs.getInt("student_id"));
                record.setStartTime(rs.getTimestamp("start_time"));
                record.setSubmitTime(rs.getTimestamp("submit_time"));
                record.setTotalScore(rs.getDouble("total_score"));
                record.setStatus(rs.getString("status"));
                return record;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean createExamRecord(ExamRecord record) {
        String sql = "INSERT INTO exam_records (exam_id, student_id, start_time, status) VALUES (?, ?, ?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            stmt.setInt(1, record.getExamId());
            stmt.setInt(2, record.getStudentId());
            stmt.setTimestamp(3, record.getStartTime());
            stmt.setString(4, record.getStatus());

            int result = stmt.executeUpdate();
            if (result > 0) {
                ResultSet keys = stmt.getGeneratedKeys();
                if (keys.next()) {
                    record.setId(keys.getInt(1));
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateExamRecord(ExamRecord record) {
        String sql = "UPDATE exam_records SET submit_time = ?, total_score = ?, status = ? WHERE id = ?";
        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setTimestamp(1, record.getSubmitTime());
            stmt.setDouble(2, record.getTotalScore());
            stmt.setString(3, record.getStatus());
            stmt.setInt(4, record.getId());

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<ExamRecord> getExamRecordsByExam(int examId) {
        List<ExamRecord> records = new ArrayList<>();
        String sql = "SELECT er.*, u.real_name FROM exam_records er " +
                "JOIN users u ON er.student_id = u.id " +
                "WHERE er.exam_id = ? ORDER BY er.submit_time DESC";

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                ExamRecord record = new ExamRecord();
                record.setId(rs.getInt("id"));
                record.setExamId(rs.getInt("exam_id"));
                record.setStudentId(rs.getInt("student_id"));
                record.setStartTime(rs.getTimestamp("start_time"));
                record.setSubmitTime(rs.getTimestamp("submit_time"));
                record.setTotalScore(rs.getDouble("total_score"));
                record.setStatus(rs.getString("status"));
                records.add(record);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return records;
    }

    public boolean startExam(int examId, int studentId) {
        // 检查是否已有记录
        ExamRecord existing = getExamRecord(examId, studentId);
        if (existing != null) {
            // 更新为进行中状态
            existing.setStatus("in_progress");
            if (existing.getStartTime() == null) {
                existing.setStartTime(new Timestamp(System.currentTimeMillis()));
            }
            return updateExamRecord(existing);
        } else {
            // 创建新记录
            ExamRecord record = new ExamRecord();
            record.setExamId(examId);
            record.setStudentId(studentId);
            record.setStartTime(new Timestamp(System.currentTimeMillis()));
            record.setStatus("in_progress");
            return createExamRecord(record);
        }
    }
}